package cn.sugarscat.flight;

import cn.sugarscat.db.DB;
import cn.sugarscat.order.Order;
import cn.sugarscat.order.OrderManager;
import cn.sugarscat.order.Payment;
import cn.sugarscat.order.PaymentManager;
import cn.sugarscat.util.Module;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Scanner;

public class FlightManager {
    public static void printFlightSeatingMap() {
        System.out.println("机舱座位示例：");
        String flightSeatingMap = """
                             ========================================================================                          =
                        =====   |               |                               |                  | ==========               ==
                    ===         |               |                               |                  |            ======      ====
                  =====   机头   | A区(MAX:200人) |       B区(MAX:500人)          |  C区(MAX:300人)   |    机尾           ==========
                    ===         |               |                               |                  |            ======      ====
                        =====   |               |                               |                  | ==========               ==
                             ========================================================================                          =
                """;

        System.out.println(flightSeatingMap);
    }

    public static boolean checkFlightId(int flightId) {
        DB db = new DB();
        String sql = "SELECT * FROM `flight` WHERE `flight_id` = ?";
        return !Module.hasThis(flightId, db, sql);
    }

    public static Flight queryFlightNumber(String number) {
        DB db = new DB();
        Flight flight = new Flight();
        flight.setId(-1);
        String sql = "SELECT * FROM `flight` WHERE `flight_number` = ?";
        ResultSet res = db.executeQuery(sql, number);
        try {
            if (res.next()) {
                flight.setId(res.getInt("flight_id"));
                flight.setFlightNumber(res.getString("flight_number"));
                flight.setDepartureLocation(res.getString("flight_departure_location"));
                flight.setDestinationLocation(res.getString("flight_destination_location"));
                flight.setDepartureTime(res.getString("flight_departure_time"));
                flight.setArrivalTime(res.getString("flight_arrival_time"));
                flight.setPrice(res.getDouble("flight_price"));
            }
            res.close();
            db.closeDB();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return flight;
    }

    public static boolean insertFlight(Flight flight) {
        DB db = new DB();
        boolean ok = false;
        String sql = "INSERT INTO `flight`(" +
                "`flight_number`, " +
                "`flight_departure_location`, " +
                "`flight_destination_location`, " +
                "`flight_departure_time`, " +
                "`flight_arrival_time`, " +
                "`flight_price`) VALUES ('" +
                flight.getFlightNumber() + "', '" +
                flight.getDepartureLocation() + "', '" +
                flight.getDestinationLocation() + "', '" +
                flight.getDepartureTime() + "', '" +
                flight.getArrivalTime() + "', '" +
                flight.getPrice() +  "');";
        if(db.executeInsert(sql)>0)
            ok = true;
        db.closeDB();
         return ok;
    }

    public static void printAllFlight() {
        DB db = new DB();
        String sql = "SELECT * FROM `flight`";
        ResultSet res = db.executeQuery(sql);
        try {
            if (res.next()) {
                System.out.println("航班ID\t航班号\t出发地\t目的地\t\t\t起飞时间\t\t\t\t\t到达时间\t\t\t价格");
                do {
                    int flightId = res.getInt("flight_id");
                    String flightNumber = res.getString("flight_number");
                    String departureLocation = res.getString("flight_departure_location");
                    String destinationLocation = res.getString("flight_destination_location");
                    String departureTime = res.getString("flight_departure_time");
                    String arrivalTime = res.getString("flight_arrival_time");
                    double price = res.getDouble("flight_price");
                    System.out.println(flightId + "\t" + flightNumber + "\t" + departureLocation +
                            "\t\t" + destinationLocation + "\t\t" + departureTime + "\t\t" + arrivalTime + "\t\t" + price);
                } while (res.next());
            } else {
                System.out.println("没有航班！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void updateFlight(int flightId, String field, String value) {
        DB db = new DB();
        String sql = "UPDATE `flight` SET `"+ field +"` = ? WHERE `flight_id` = ?;";
        if(db.executeUpdate(sql, value, ""+flightId)>0)
            System.out.println("修改成功！");
        else
            System.out.println("修改失败！");
        db.closeDB();
    }

    public static void deleteFlight(int flightId) {
        DB db = new DB();
        String sql = "DELETE FROM `flight` WHERE `flight_id` = ?";
        db.executeDelete(sql, ""+flightId);
        db.closeDB();
    }

    public static void queryFlightsInfo(String  departure, String destination) {
        DB db = new DB();
        String sql = "SELECT * FROM `flight`" +
                "WHERE `flight_departure_location` LIKE ?" +
                "OR `flight_destination_location` LIKE ?;";
        ResultSet res = db.executeQuery(sql, "%" + departure + "%", "%" + destination + "%");
        try {
            if (res.next()) {
                printFlightsInfo(res);
            } else {
                System.out.println("没有航班信息！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static void printFlightsInfo(ResultSet res) throws SQLException {
        System.out.println("航班号\t出发地\t目的地\t\t\t起飞时间\t\t\t\t\t到达时间\t\t\t价格");
        do {
            String flightNumber = res.getString("flight_number");
            String departureLocation = res.getString("flight_departure_location");
            String destinationLocation = res.getString("flight_destination_location");
            String departureTime = res.getString("flight_departure_time");
            String arrivalTime = res.getString("flight_arrival_time");
            double price = res.getDouble("flight_price");
            System.out.println(flightNumber + "\t" + departureLocation +
                    "\t\t" + destinationLocation + "\t\t" + departureTime + "\t\t" + arrivalTime + "\t\t" + price);
        } while (res.next());
    }

    public static void queryFlightsInfo(String  departure, String destination, String departureTime) {
        DB db = new DB();
        String sql = "SELECT * FROM `flight`" +
                "WHERE `flight_departure_location` LIKE ?" +
                "OR `flight_destination_location` LIKE ?" +
                "OR `flight_departure_time` LIKE ?;";
        ResultSet res = db.executeQuery(sql, "%" + departure + "%", "%" +
                destination + "%", "%" + departureTime + "%");
        try {
            if (res.next()) {
                printFlightsInfo(res);
            } else {
                System.out.println("没有航班信息！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void bookTicket(int uid, Flight flight) {
        Order order = new Order();
        order.setUserId(uid);
        order.setFlightId(flight.getId());
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入您的真实姓名：");
        order.setPassengerName(scanner.next());
        System.out.print("请输入您的性别：");
        order.setPassengerGender(scanner.next());
        System.out.print("请输入您的生日(示例：01-01)：");
        order.setPassengerDob(scanner.next());
        printFlightSeatingMap();
        String seatArea;
        int setId;
        while (true) {
            System.out.print("请输入你想要的座位区域：");
            seatArea = scanner.next();
            if (!(Objects.equals(seatArea, "A") ||
                    Objects.equals(seatArea, "B") ||
                    Objects.equals(seatArea, "C"))) {
                System.out.println("输入有误，请重新输入！");
            } else {
                setId = SeatManager.querySeatId(flight.getId(), seatArea);
                if (setId!=-1) {
                    System.out.println("占座中···");
                    if (SeatManager.bookSeat(setId)) {
                        System.out.println("占座成功！");
                    } else {
                        System.out.println("占座失败！请重新选择。");
                        continue;
                    }
                    break;
                } else {
                    System.out.println("此区域座位已售空，请重新选择！");
                }
            }
        }
        order.setSeatId(setId);
        order.setStatus("未支付");
        System.out.println("生成订单中···");
        if (!OrderManager.insertOrder(order)) {
            System.out.println("订单创建失败！");
            return;
        }
        order.setId(OrderManager.queryOrderInfo(uid, flight.getId()));
        System.out.println("订单创建成功！");
        System.out.print("请输入支付方式：");
        String payMethod = scanner.next();
        Payment payment = new Payment(order.getId(), flight.getPrice(), payMethod, Module.timeToString(LocalDateTime.now()));
        System.out.println("支付中···");
        if (PaymentManager.insertPayment(payment)) {
            System.out.println("支付成功！");
            OrderManager.updateOrderStatus(order.getId(), "已支付");
            System.out.println("机票预定成功！");
        } else {
            System.out.println("支付失败！");
        }
    }
}
